package com.dodayum.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dodayum.entity.FileEntity;
import com.dodayum.mapper.FileMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * Author:dodayum
 * Date:2025-06-30
 */
@Service
public class FileService {

    @Resource
    FileMapper fileMapper;
    @Resource
    private MinioService minioService;

    public void save(MultipartFile multipartFile, String remark) throws Exception {
        String minioFileName = minioService.save(multipartFile);
        String originalFilename = multipartFile.getOriginalFilename();
        FileEntity fileEntity = new FileEntity();
        fileEntity.setName(originalFilename);
        fileEntity.setMinioFileName(minioFileName);
        fileEntity.setRemark(remark);
        fileMapper.insert(fileEntity);
    }

    public FileEntity getInfoById(Long id) {
        return fileMapper.selectById(id);
    }

    public byte[] getFileById(Long id) throws Exception {
        FileEntity fileEntity = fileMapper.selectById(id);
        if (fileEntity.getIsDelete()){
            return null;
        }
        String minioFileName = fileEntity.getMinioFileName();
        return minioService.get(minioFileName);
    }

    public void deleteById(Long id) throws Exception {
        FileEntity fileEntity = fileMapper.selectById(id);
        if (ObjectUtils.isEmpty(fileEntity)){
            return;
        }
        String minioFileName = fileEntity.getMinioFileName();
        fileMapper.deleteById(id);
        minioService.delete(minioFileName);
    }

    public void deleteFileByIds() throws Exception {
        List<FileEntity> fileEntities = fileMapper.selectList(new LambdaQueryWrapper<>());
        for (FileEntity fileEntity : fileEntities) {
            this.deleteById(fileEntity.getId());
        }
    }
}
